<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/19
 * Time: 15:53
 */

namespace app\event;


use app\common\lib\Common;
use support\Db;

class RequestEvent
{
    public function terminate($data)
    {
        list($request,$response) = $data;

        //调试模式才能记录调试日记
        if(method_exists($response,'rawBody')){
            //todo 1 记录SQL语句
            if(!empty($request->sqllogDebug)){
                $request->sqllogDebug = array_filter(explode("\n",$request->sqllogDebug));
                $content = '['.$request->url().'] '.$request->method()."\n";
                foreach($request->sqllogDebug as $log){
                    if(strpos($log,'select 1')===false){
                        $content .= $log."\n";
                    }
                }

                Common::createAndSaveLog($content."\n------------------------------------------------------------\n\n",'sql');
            }

            //todo 2 记录每次请求的参数和返回数据
            $responseData = json_decode($response->rawBody(),true)??[];
            $responseData['result'] = $request->reponseResult??[];
            $headers = array_merge($request->header(),['ip'=>$request->getRealIp()]);

            $headerParam = json_encode($headers, 256);
            $requestParam = json_encode($request->allParam, 256);
            $responseParam = json_encode($responseData,256);
            $paramContent = '['.$request->url().'] '.$request->method()."\n";
            $paramContent .= "header: ".$headerParam."\n";
            $paramContent  .= "requestParam: ".$requestParam."\n";
            $paramContent  .= "responseData: ".$responseParam."\n";

            $execTime = round(microtime(true)-$request->startExceTime,3);
            $paramContent  .= "execTime: ".round(microtime(true)-$request->startExceTime,3)."\n"."\n";

            //后台接口不通知
            if($execTime>5 && strpos($request->path(),'/app/admin/')===false){
                Common::saveOverTimeLog(round($execTime));
            }
            //var_dump($paramContent);
            Common::createAndSaveLog($paramContent,'request');
        }

    }
}